package com.zxt.content.common.utils;

import com.zxt.bean.Result;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;

public class ValidateUtil {
    private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    public ValidateUtil() {
    }

    public static <T> Result validate(T object, String msg, Class<?>... groups) {
        if (object == null) {
            return Result.newError(msg);
        } else {
            if (Objects.isNull(groups)) {
                groups = new Class[0];
            }

            Set<ConstraintViolation<T>> validator = factory.getValidator().validate(object, groups);
            return validator != null && validator.iterator().hasNext() ? Result.newError(((ConstraintViolation) validator.iterator().next()).getMessage()) : null;
        }
    }

    public static <T> Result validate(List<T> object, String msg, Class<?>... groups) {
        if (object != null && !object.isEmpty()) {
            Iterator var3 = object.iterator();
            if (var3.hasNext()) {
                T t = (T) var3.next();
                return validate(t, msg, groups);
            } else {
                return null;
            }
        } else {
            return Result.newError(msg);
        }
    }
}
